package rest.o.gram.tasks;

import android.os.AsyncTask;
import android.util.Log;
import org.json.rpc.client.HttpJsonRpcClientTransport;
import org.json.rpc.client.JsonRpcInvoker;
import rest.o.gram.RestogramService;
import rest.o.gram.RestogramVenue;

/**
 * Created with IntelliJ IDEA.
 * User: or_2
 * Date: 4/20/13
 */
public class QueryNearbyTask extends AsyncTask<String, Void, RestogramVenue[]> {

    public QueryNearbyTask(HttpJsonRpcClientTransport transport, ITaskObserver observer) {
        this.transport = transport;
        this.observer = observer;
    }

    @Override
    protected RestogramVenue[] doInBackground(String... params) {
        JsonRpcInvoker invoker = new JsonRpcInvoker();
        RestogramService service = invoker.get(transport, "restogram", RestogramService.class);

        final double lat = Double.parseDouble(params[0]);
        final double lon = Double.parseDouble(params[1]);
        return safeQueryNearby(service, lat, lon, params[2]);
    }

    @Override
    protected void onPostExecute(RestogramVenue[] result) {
        observer.onFinished(result);
    }

    private  RestogramVenue[] safeQueryNearby(RestogramService service,
                                              double lat, double lon, String query){
        try
        {
            return service.getNearby(lat, lon, query);
        }
        catch (Exception e)
        {
            Log.e("REST-O-GRAM", "QUERY NEARBY - FIRST ATTEMPT FAILED");
            e.printStackTrace();
            return service.getNearby(lat, lon, query);
        }
    }

    private HttpJsonRpcClientTransport transport;
    private ITaskObserver observer;
}
